const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const User = require('../models/User');

// 获取所有用户
router.get('/', auth, async (req, res) => {
  try {
    const users = await User.find().populate('roles');
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取单个用户
router.get('/:id', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.id).populate('roles');
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户
router.put('/:id', auth, async (req, res) => {
  try {
    const { username, email, roles } = req.body;
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { username, email, roles },
      { new: true }
    ).populate('roles');
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    res.json(user);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除用户
router.delete('/:id', auth, async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    res.json({ message: '用户已删除' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 